package cn.vendai.com.initializer;

import cn.vendai.com.entity.Message;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 初始化MongoDB索引
 * 为Message实体类的createdAt字段创建升序索引，并设置过期时间为expireDays天
 */
@Component
public class MongoIndexInitializer {

    /**
     * 过期时间(单位:小时)
     */
    private final MongoTemplate mongoTemplate;

    /**
     * 过期时间(单位:小时)
     */
    private final long expireDays;

    public MongoIndexInitializer(MongoTemplate mongoTemplate,
                                 @Value("${chat.conversation-expire-hours}") long expireDays) {
        this.mongoTemplate = mongoTemplate;
        this.expireDays = expireDays;
    }

    @PostConstruct
    public void initIndexes() {
        mongoTemplate.indexOps(Message.class)
                .ensureIndex(new Index()
                        .on("createdAt", org.springframework.data.domain.Sort.Direction.ASC)
                        .expire(expireDays, TimeUnit.DAYS));
    }
}
